package bavaria.hightech.testit.pruefungen.ss09;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class CircularListImpl<T> implements CircularList<T> {
	
	private List<T> list;
	
	public CircularListImpl() {
		this.list = new ArrayList<T>();
	}
	
	public CircularListImpl(Class<?> clazz) throws InstantiationException, IllegalAccessException{
		this.list = (List<T>) clazz.newInstance();
	}

	@Override
	public void add(T t) {
		this.list.add(t);
	}

	@Override
	public boolean constrains(T t) {
		return this.list.contains(t);
	}

	@Override
	public List<T> asList() {
		return Collections.unmodifiableList(this.list);
	}
	
	public String toString(){
		String s = "";
		for (T element : this.list) {
			s += element.toString() +",";
		}
		s += "...";
		return s;
	}
	
	
	public boolean equals(Object o){
			CircularListImpl<T> cl = (CircularListImpl<T>) o;
			if(this.list.equals(cl.asList())){
				return true;
		}
		return false;
	}
	
	public List<T> getList(){
		return this.list;
	}
	public Iterator<T> iterator(){
		return new Itr<T>();
	}
	
	@SuppressWarnings("hiding")
	private class Itr<T> implements Iterator<T>{
		
		private int cursor = 0;

		@Override
		public boolean hasNext() {			
			return true;
			}

		@Override
		public T next() {

			T element = (T) CircularListImpl.this.list.get(cursor);
			if(cursor == CircularListImpl.this.list.size()-1	){
				cursor = 0;
			}else{
			cursor++;
			}
			
			return element;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
			
		}
		
	}

}
